package server

import (
	"encoding/json"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"go-block-1/core"
	"io"
	"io/ioutil"
	"net/http"
	"strconv"
)
//实例化区块链
var  b = core.NewBlockChain()

//旷工节点地址
var node = GetUuid()

func NewTrabsaction(w http.ResponseWriter, r *http.Request)  {
	body,err := ioutil.ReadAll(r.Body)

	if err != nil {
		fmt.Printf("read body err, %v\n",err)
		return
	}
	var transaction core.Transaction
	
	json.Unmarshal(body, &transaction)
	b.NewTransaction(transaction.Sender,transaction.Recipient,transaction.Amount)
	io.WriteString(w,"will add new transaction on block")
}


//挖矿
func Mine(w http.ResponseWriter, r *http.Request)  {
	lastProof := b.LastBlock().Proof
	proof := b.ProofOfWork(lastProof)
	
	//成功挖矿给自己转账，旷工奖励机制
	b.NewTransaction("0",node,1)
	block := b.NewBlock(proof)
	b.Chain = append(b.Chain,*block)
	io.WriteString(w,BlockToJson(block))
}

func GetUuid() string {
	return uuid.NewV4().String()

}


func BlockToJson(block *core.Blcok) string {
	bytes, _ := json.MarshalIndent(block, "", "")

	return string(bytes)
}


//查看整个链
func FullChain(w http.ResponseWriter, r *http.Request)  {
	io.WriteString(w,b.BlockChainToJson())
}


//注册节点，发挥所有节点信息
func NodeRegister(w http.ResponseWriter, r *http.Request)  {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Printf("read body err %v\n",err)
		return
	}
	var s []string
	json.Unmarshal(body,&s)

	for _,value := range s{
		fmt.Println(value)
		b.RegisterNode(value)
	}
	
	io.WriteString(w,b.GetNodes())
}

func ResolveConfict(w http.ResponseWriter, r *http.Request)  {
	replaced := b.ResolveConflict()
	io.WriteString(w,"block chain relaced:"+strconv.FormatBool(replaced))
}